package com.frame.system.controller;

import com.frame.common.core.entity.SysUser;
import com.frame.common.core.security.entity.SecurityUser;
import com.frame.common.core.security.utils.SecurityUtils;
import com.frame.common.core.security.utils.TokenUtil;
import com.frame.security.service.ISysUserService;
import com.frame.stant.constans.UserConstants;
import com.frame.stant.utils.R;
import com.frame.stant.utils.ServletUtils;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @author ruoyi
 */
@Api(tags = "个人信息")
@RestController
@RequestMapping("/system/user/profile")
@AllArgsConstructor
public class SysProfileController  {

    private final ISysUserService userService;
    private final TokenUtil tokenService;

    /**
     * 个人信息
     */
    @GetMapping
    public R profile() {
        SecurityUser loginUser = tokenService.getCurrentUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        R result = R.success(user);
        Map map = Maps.newHashMap();
        map.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        map.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        result.setData(map);
        return result;
    }

    /**
     * 修改用户
     */
//    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public R updateProfile(@RequestBody SysUser user) {
        if (StringUtils.isNotEmpty(user.getPhoneNumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(user) > 0) {
            SecurityUser loginUser = tokenService.getCurrentUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setNickName(user.getNickName());
            loginUser.getUser().setPhoneNumber(user.getPhoneNumber());
            loginUser.getUser().setEmail(user.getEmail());
            loginUser.getUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return R.success();
        }
        return R.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
//    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public R updatePwd(String oldPassword, String newPassword) {
        SecurityUser loginUser = tokenService.getCurrentUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return R.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return R.error("新密码不能与旧密码相同");
        }
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return R.success();
        }
        return R.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
//    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public R avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
//            SecurityUser loginUser = tokenService.getCurrentUser(ServletUtils.getRequest());
//            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file);
//            if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
//                R ajax = R.success();
//                ajax.put("imgUrl", avatar);
//                // 更新缓存用户头像
//                loginUser.getUser().setAvatar(avatar);
//                tokenService.setLoginUser(loginUser);
//                return ajax;
//            }
        }
        return R.error("上传图片异常，请联系管理员");
    }
}
